import 'dart:ui' as ui;
import 'dart:async';
import 'dart:typed_data';
import 'dart:ui';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_rider/main/widgets/state/state_layout.dart';
import 'package:flutter_rider/main/widgets/ui_constant.dart';
import 'package:flutter_rider/utils/screen_fit.dart';
import 'package:flutter_rider/config.dart';
import 'package:flutter_rider/generated/r.dart';
import 'package:flutter_rider/utils/log.dart';
import 'package:flutter_rider/utils/extension.dart';
import 'package:amap_flutter_map/amap_flutter_map.dart';
import 'package:amap_flutter_base/amap_flutter_base.dart';
import 'package:flutter_svg/flutter_svg.dart';

import '../../../event/loc_top_event.dart';
import '../../../event/refresh_map_event.dart';
import '../../../event/refresh_order_event.dart';
import '../../../event/task_to_map_event.dart';
import '../../../main.dart';

class TaskDetailMapPage extends StatefulWidget {
  int orderStatus;
  int? distance;
  int? eta;
  double? locTop;
  double? carLat;
  double? carLng;
  List? stations;
  double? mapHeight;

  TaskDetailMapPage(this.orderStatus,
      {this.distance,
      this.eta,
      this.locTop,
      this.carLat,
      this.carLng,
      this.stations,
      this.mapHeight,
      Key? key})
      : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return TaskDetailMapPageState();
  }
}

class TaskDetailMapPageState extends State<TaskDetailMapPage>
    with WidgetsBindingObserver {
  dynamic _data;
  AMapController? _mapController;
  final Map<String, Marker> _markers = <String, Marker>{};
  final Map<String, Polyline> _polylines = <String, Polyline>{};
  late StreamSubscription _eventFn;
  late StreamSubscription _eventFn1;
  late StreamSubscription _eventFn2;
  var _isLoading = false;
  final StateLayoutController _stateLayoutController = StateLayoutController();
  Timer? _refreshTimer;
  bool _hasOkLoad = false;

  /// 地图缩放比例
  double _curZoom = 16;
  bool _isPageShow = true;
  var _stationMd5 = "";
  bool flag = true;
  int _account = 0;
  double locTop = 200;
  double mapHeight = 600;

  AMapWidget? map;
  Map<String, Marker> initMarkerMap = <String, Marker>{};

  @override
  Widget build(BuildContext context) {
    return Material(
        child: StateLayout(
      url: "/home/index?station_md5=$_stationMd5",
      controller: _stateLayoutController,
      dataCallback: _onDataCallback,
      childBuilder: _renderContent,
      errorCallback: (_, __) {
        setState(() {
          _isLoading = false;
        });
      },
    ));
  }

  @override
  void initState() {
    super.initState();

    _eventFn = eventBus.on<TaskToMapEvent>().listen((event) {
      _stateLayoutController.reload();
    });

    _eventFn1 = eventBus.on<LocToptEvent>().listen((event) {
      print(event.top);
      setState(() {
        locTop = event.top;
        mapHeight = event.height;
      });

    });

    _eventFn2 = eventBus.on<RefreshMapEvent>().listen((event) {
      _account = 1;
    });

    WidgetsBinding.instance?.addObserver(this);
  }

  @override
  void dispose() {
    super.dispose();
    _refreshTimer?.cancel();
    _mapController?.disponse();
    _eventFn.cancel();
    _eventFn1.cancel();
    _eventFn2.cancel();
    WidgetsBinding.instance?.removeObserver(this);
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    switch (state) {
      case AppLifecycleState.resumed:
        Log.i("resumed");
        _isPageShow = true;
        break;
      case AppLifecycleState.inactive:
        Log.i("inactive");
        _isPageShow = false;
        break;
      case AppLifecycleState.paused:
        Log.i("paused");
        break;
      case AppLifecycleState.detached:
        Log.i("detached");
        break;
    }
  }

  ///自定义地图mark的 widget转字节
  Future<ByteData?> widgetToByteData(Widget widget,
      {Alignment alignment = Alignment.center,
      Size size = const Size(double.maxFinite, double.maxFinite),
      double devicePixelRatio = 1.0,
      double pixelRatio = 1.0}) async {
    RenderRepaintBoundary repaintBoundary = RenderRepaintBoundary();

    RenderView renderView = RenderView(
      child: RenderPositionedBox(alignment: alignment, child: repaintBoundary),
      configuration: ViewConfiguration(
        size: size,
        devicePixelRatio: devicePixelRatio,
      ),
      window: ui.window,
    );

    PipelineOwner pipelineOwner = PipelineOwner();
    pipelineOwner.rootNode = renderView;
    renderView.prepareInitialFrame();

    BuildOwner buildOwner = BuildOwner(focusManager: FocusManager());
    RenderObjectToWidgetElement rootElement = RenderObjectToWidgetAdapter(
      container: repaintBoundary,
      child: widget,
    ).attachToRenderTree(buildOwner);
    buildOwner.buildScope(rootElement);
    buildOwner.finalizeTree();

    pipelineOwner.flushLayout();
    pipelineOwner.flushCompositingBits();
    pipelineOwner.flushPaint();

    ui.Image image = await repaintBoundary.toImage(pixelRatio: pixelRatio);
    ByteData? byteData = await image.toByteData(format: ui.ImageByteFormat.png);

    return byteData;
  }

  ///自定义widget
  widgetContext(String stationName, int type, String snippet) {
    List arr = widget.stations ?? [];
    return Container(
      width: 550.rpx,
      height: 490.rpx,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          Text(type == 0 || type == 1 ? stationName : "",
              style: TextStyle(
                  color: const Color(0xFF58BCC7),
                  fontSize: 36.rpx,
                  fontWeight: FontWeight.w600),
              textDirection: TextDirection.ltr),
          // type == 0?0.hspace:20.hspace,
          type == 0
              ? Container(
                  width: 90.rpx,
                  height: 120.rpx,
                  alignment: Alignment.centerLeft,
                  decoration: const BoxDecoration(
                    image: DecorationImage(
                      image: AssetImage('assets/image/poi/map_fa.png'),
                      fit: BoxFit.fitHeight, // 完全填充
                    ),
                  ),
                )
              : type == 1
                  ? Container(
                      width: 90.rpx,
                      height: 120.rpx,
                      alignment: Alignment.centerLeft,
                      decoration: const BoxDecoration(
                        image: DecorationImage(
                          image: AssetImage('assets/image/poi/map_shou.png'),
                          fit: BoxFit.fitHeight, // 完全填充
                        ),
                      ),
                    )
                  : Container(
                      width: 340.rpx,
                      height: 240.rpx,
                      decoration: const BoxDecoration(
                        // border: Border.all(width: 1.rpx,color: UIColor.color_primary),
                        image: DecorationImage(
                          image:
                              AssetImage('assets/image/poi/car_map_task.png'),
                          fit: BoxFit.fitWidth, // 完全填充
                        ),
                      ),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          snippet == "" ? 60.hspace : 40.hspace,
                          Text(
                            stationName,
                            style: TextStyle(
                                color: const Color(0xFF000000),
                                fontSize: 36.rpx),
                            textDirection: TextDirection.ltr,
                          ),
                          Text(
                            snippet,
                            style: TextStyle(
                                color: UIColor.color_primary, fontSize: 36.rpx),
                            textDirection: TextDirection.ltr,
                          ),
                        ],
                      )),
        ],
      ),
    );
  }

  _onDataCallback(dynamic data) async {
    _hasOkLoad = true;
    _data = data;
    if (_account < 2) {
      renderStation();
      // flag = false;
      // calcCluster();
      _account++;
    } else {
      calcCluster();
      renderLine();
    }
  }

  Widget _renderContent(dynamic data) {
    var size = MediaQuery.of(context).size;
    double screen01percentage = MediaQuery.of(context).size.height * 0.1;
    return SizedBox(
      width: size.width,
      height: mapHeight,
      child: Stack(
        children: [
          _renderMap(),
          Column(
            children: [
              // 200.hspace,

              /// 我的位置
              _renderResetLoc(),
            ],
          ),
          Container(
            width: 50.rpx,
            margin: EdgeInsets.only(top: 36.rpx),
            child: GestureDetector(
              onTap: (){
                Navigator.of(context).pop();
                eventBus.fire(RefreshOrderEvent());
              },
              child: SvgPicture.asset(R.image_chevron_left,width: 32.rpx,height: 32.rpx,),
            )
            // IconButton(
            //   iconSize: 20.rpx,
            //   icon: const Icon(
            //     Icons.arrow_back_ios_new,
            //     color: UIColor.color_t1,
            //   ),
            //   onPressed: () {
            //     Navigator.of(context).pop();
            //     eventBus.fire(RefreshOrderEvent());
            //   },
            // ),
          ),

          /// 背景滤镜
          // Container(
          //   height: 40.rpx,
          //   width: 90.rpx,
          //   margin: EdgeInsets.only(top: 220.rpx),
          //   child: ClipRRect( // make sure we apply clip it properly
          //     child: BackdropFilter( //背景滤镜
          //       filter: ImageFilter.blur(sigmaX: 2, sigmaY: 2),
          //       child: Container(
          //         alignment: Alignment.center,
          //         color: Colors.grey.withOpacity(0.1),
          //       ),
          //     ),
          //   ),
          // )
        ],
      ),
    );
  }

  /// 渲染站点
  renderStation() async {
    Map<String, Marker> tmpMarkers = {};
    //显示收货站点
    if (widget.stations != null) {
      List arr = widget.stations ?? [];
      for (var i = 0; i < arr.length; i++) {
        ByteData? byteData =
            await widgetToByteData(widgetContext(arr[i]["stationName"], i, ''));
        var icon = BitmapDescriptor.fromBytes(byteData!.buffer.asUint8List());
        tmpMarkers["s_${arr[i]["id"]}"] = Marker(
          zIndex: 1,
          position: LatLng(toDouble(arr[i]["lat"]), toDouble(arr[i]["lng"])),
          // infoWindow: InfoWindow(title: arr[i]["stationName"]),
          // infoWindowEnable: true,
          icon: icon,
        );
      }
    }
    setState(() {
      _markers.addAll(tmpMarkers);
    });

    calcCluster();
    renderLine();
  }

  /// 渲染路线
  renderLine() {
    Map<String, Polyline> tmpPolylines = {};
    List arr = widget.stations ?? [];
    List<LatLng> points = [];
    // if(arr.length ==2 && arr[1]["lat"]!=0 && arr[1]["lat"] !=0) {

    // orderStatus 0 未分配  1待装货  2待卸货 3已完成 -1已取消
    var pt1 = const LatLng(0.0, 0.0);
    var pt2 = const LatLng(0.0, 0.0);
    // 待装货的订单，车辆连向发货地
    if (widget.orderStatus == 1) {
      if (widget.carLat != 0 && widget.carLng != 0 && arr[0]["lat"]!=0 && arr[0]["lng"]!=0) {
        pt1 = LatLng(toDouble(widget.carLat), toDouble(widget.carLng));
        pt2 = LatLng(toDouble(arr[0]["lat"]), toDouble(arr[0]["lng"]));
      } else {
        return false;
      }
    }
    // 待卸货的订单，车辆连向卸货地[]
    else if (widget.orderStatus == 2) {
      if (widget.carLat != 0 && widget.carLng != 0 && arr[1]["lat"]!=0 && arr[1]["lng"]!=0) {
        pt1 = LatLng(toDouble(widget.carLat), toDouble(widget.carLng));
        pt2 = LatLng(toDouble(arr[1]["lat"]), toDouble(arr[1]["lng"]));
      } else {
        return false;
      }
    }
    // 发货地连向卸货地
    else {
      if(arr[0]["lat"]>0 && arr[0]["lng"]>0 && arr[1]["lat"]>0 && arr[1]["lng"]>0){
        pt1 = LatLng(toDouble(arr[0]["lat"]), toDouble(arr[0]["lng"]));
        pt2 = LatLng(toDouble(arr[1]["lat"]), toDouble(arr[1]["lng"]));
      } else {
        return false;
      }
    }

    // var pt1= LatLng(toDouble(arr[0]["lat"]), toDouble(arr[0]["lng"]));
    // var pt2 = LatLng(toDouble(arr[1]["lat"]), toDouble(arr[1]["lng"]));
    var distance = AMapTools.distanceBetween(pt1, pt2);
    // 大于5m才划线，小于默认为到达目的地
    if (distance > 5) {
      points.add(pt1);
      points.add(pt2);
      final Polyline polyline = Polyline(
          width: 15,
          joinType: JoinType.round,
          capType: CapType.round,
          geodesic: true,
          customTexture:
              BitmapDescriptor.fromIconPath(R.image_poi_texture_line1),
          points: points);
      tmpPolylines["c_${arr[1]["id"]}"] = polyline;
    }
    setState(() {
      _polylines.clear();
      _polylines.addAll(tmpPolylines);
    });
    // }
  }

  /// 渲染车辆
  calcCluster() async {
    /// orderStatus 0 未分配  1待装货  2待卸货 3已完成 -1已取消
    /// 未分配，已完成，已取消不需要显示车辆图标
    if (widget.orderStatus == 0 || widget.orderStatus == 3 || widget.orderStatus == -1) return false;
    List arr = widget.stations ?? [];
    //var pt1;
    // if() {
    //
    // }
    // if(widget.carLat !=0 && widget.carLng !=0) {
    // 待卸货无车时[未分配装货后，则待卸货无车]
    var pt1 = const LatLng(0.0, 0.0);
    if(widget.carLat==0 || widget.carLng==0) return false;

    pt1 = LatLng(toDouble(widget.carLat), toDouble(widget.carLng));
    // }
    // if(pt1 == null) {
    // 如果没车终止下面执行不走
    // return false;
    // }

    var pt2 = const LatLng(0.0, 0.0);

    /// 待装货，取发货站点
    if (widget.orderStatus == 1 && arr[0]["lat"] > 0 && arr[0]["lng"] > 0) {
        pt2 = LatLng(toDouble(arr[0]["lat"]), toDouble(arr[0]["lng"]));
    }

    /// 待卸货，去收货站点
    if (widget.orderStatus == 2 && arr[1]["lat"] > 0 && arr[1]["lng"] > 0) {
        pt2 = LatLng(toDouble(arr[1]["lat"]), toDouble(arr[1]["lng"]));
    }

    /// 车的位置与发货站点或者卸货站点的位置
    var distance = AMapTools.distanceBetween(pt1, pt2);
    var title = "", snippet ="";

    // 计算经纬度两点间的距离大于5则赶往目的地
    if (distance > 0) {
      title = widget.orderStatus == 1? "正赶往装货地": widget.orderStatus == 2? "正赶往卸货地": "";
      snippet = "距离${widget.distance}m | ${widget.eta}分钟";
    } else {
      title = widget.orderStatus == 1? "已到达装货地": widget.orderStatus == 2? "已到达卸货地": "";
      snippet = "";

      /// 清除定时刷新
      // eventBus.fire(
      //     RefreshOrderEvent());
    }

    Map<String, Marker> tmpMarkers = {};
    ByteData? byteData =
        await widgetToByteData(widgetContext(title, 2, snippet));
    var icon = BitmapDescriptor.fromBytes(byteData!.buffer.asUint8List());

    // BitmapDescriptor icon;
    // icon =  BitmapDescriptor.fromIconPath(R.image_poi_car_map_task);
    tmpMarkers["m_1"] = Marker(
      zIndex: 1,
      position: LatLng(toDouble(widget.carLat), toDouble(widget.carLng)),
      icon: icon,
      // infoWindow: InfoWindow(title:title, snippet: snippet),
      // infoWindowEnable: true,
    );
    // tmpMarkers["m_1"] = marker;
    /// 车辆经纬度没发生变化就不重新渲染
    if (distance > 0) {
      _markers.removeWhere((key, value) {
        return key.startsWith("m_");
      });
    }
    setState(() {
      _markers.addAll(tmpMarkers);
    });
    _isLoading = false;
  }

  /// 我的位置
  Widget _renderResetLoc() {
    return Container(
      margin: EdgeInsets.only(top: locTop),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          GestureDetector(
            onTap: () {
              setState(() {
                _isLoading = true;
              });
              _stateLayoutController.reload();
              _moveToPosition();
            },
            child: Card(
              child: SizedBox(
                width: 44.rpx,
                height: 44.rpx,
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    _isLoading
                        ? SizedBox(
                        width: 20.rpx,
                        height: 20.rpx,
                        child: CircularProgressIndicator(
                          strokeWidth: 2.rpx,
                          color: UIColor.color_t3,
                        ))
                        : Icon(Icons.my_location_sharp,
                        size: 24.rpx, color: const Color(0xff54BD95)),
                  ],
                ),
              ),
            ),
          ),
          10.wspace,
        ],
      )
    );
  }

  /// 初始化地图
  Widget _renderMap() {
    List arr = widget.stations ?? [];
    // 发货地址和收货地址同时存在的时候，中心点取中间的中心，否则取发货地址
    double lat = 0;
    double lng = 0;
    if (arr.length == 2) {
      if (arr[0]["lat"] != 0 &&
          arr[0]["lng"] != 0 &&
          arr[1]["lat"] != 0 &&
          arr[1]["lng"] != 0) {
        //计算两个经纬度中心点位置
        //oneLon：第一个点的经度；oneLat：第一个点的纬度；twoLon：第二个点的经度；twoLat：第二个点的纬度；
        var _lng = 0.0, _lat = 0.0;
        double bLon = toDouble(arr[0]["lng"]) - toDouble(arr[1]["lng"]);
        double bLat = toDouble(arr[0]["lat"]) - toDouble(arr[1]["lat"]);
        //Math.abs()绝对值
        if (bLon > 0) {
          _lng = toDouble(arr[0]["lng"]) - bLon.abs() / 2;
        } else {
          _lng = toDouble(arr[1]["lng"]) - bLon.abs() / 2;
        }
        if (bLat > 0) {
          _lat = arr[0]["lat"] - bLat.abs() / 2;
        } else {
          _lat = arr[1]["lat"] - bLat.abs() / 2;
        }
        // lat = toDouble(arr[1]["lat"]);
        // lng = toDouble(arr[1]["lng"]);

        lng = _lng;
        lat = _lat;
        //AMapTools.getCenterLonLat(arr[0]["lat"], arr[0]["lng"],arr[1]["lat"],arr[1]["lng"]);
      } else {
        lat = toDouble(arr[0]["lat"]);
        lng = toDouble(arr[0]["lng"]);
      }
    } else {
      lat = toDouble(arr[0]["lat"]);
      lng = toDouble(arr[0]["lng"]);
    }

    /// 如果发货站点与收货站点太近的时候，将地图放大
    /// 当有发货站点和收货站点的时候进行距离计算
    if (arr.length == 2) {
      var pt1 = LatLng(toDouble(arr[0]["lat"]), toDouble(arr[0]["lng"]));
      var pt2 = LatLng(toDouble(arr[1]["lat"]), toDouble(arr[1]["lng"]));
      var distance = AMapTools.distanceBetween(pt1, pt2);

      if (distance < 300) {
        _curZoom = 17;
      }
      if (distance < 200) {
        _curZoom = 17.5;
      }
      if (distance < 100) {
        _curZoom = 18;
      }
      if (distance < 50) {
        _curZoom = 20;
      }
    }

    return AMapWidget(
      apiKey: const AMapApiKey(
          androidKey: Config.androidAmapKey, iosKey: Config.iOSAmapKey),
      onMapCreated: _onMapCreated,
      privacyStatement: const AMapPrivacyStatement(
          hasContains: true, hasShow: true, hasAgree: true),
      initialCameraPosition:
          CameraPosition(target: LatLng(lat, lng), zoom: _curZoom),
      markers: Set<Marker>.of(_markers.values),
      polylines: Set<Polyline>.of(_polylines.values),
      buildingsEnabled: false,
      labelsEnabled: false,
      onCameraMove: (position) {
        /// 缩放地图重新渲染车辆
        // var delt = position.zoom - _curZoom;
        // if (delt > 0.5 || delt < -0.5) {
        //   _curZoom = position.zoom;
        //   calcCluster();
        // }
      },
    );
  }

  _onMapCreated(AMapController controller) {
    setState(() {
      _mapController = controller;
      //_moveToPosition();
    });
  }

  /// 重新进行地图缩放
  _moveToPosition() {
    var pt = _data["center_info"];
    _mapController?.moveCamera(
      CameraUpdate.newCameraPosition(
        CameraPosition(
            target: LatLng(toDouble(pt["lat"]), toDouble(pt["lng"])),
            zoom: 16,
            tilt: 0,
            bearing: 0),
      ),
      animated: true,
    );
  }

  @override
  void setState(fn) {
    //重写setState，加一个安全判断，Widget是否安装在tree上
    if (mounted) {
      super.setState(fn);
    }
  }
}
